package view;

import dao.ProductDAO;
import model.Admin;
import model.Product;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

public class ProductManageFrame extends JFrame {
    private ProductDAO productDAO;
    private JTable productTable;
    private DefaultTableModel tableModel;
    private JTextField productNameField;
    private JTextField priceField;
    private JTextField categoryField;
    private JTextField quantityField;
    private JButton addButton;
    private JButton deleteButton;
    private JButton updateButton;
    private JButton backButton;

    public ProductManageFrame() {
        productDAO = new ProductDAO();

        // 设置窗口属性
        setTitle("在线购物系统 - 商品管理");
        setSize(900, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 创建主面板
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());
        mainPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));

        // 创建表格模型
        tableModel = new DefaultTableModel();
        tableModel.addColumn("商品ID");
        tableModel.addColumn("商品名称");
        tableModel.addColumn("价格");
        tableModel.addColumn("类别");
        tableModel.addColumn("库存数量");

        // 创建商品表格
        productTable = new JTable(tableModel);
        productTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        productTable.setFillsViewportHeight(true);

        // 创建表格滚动面板
        JScrollPane scrollPane = new JScrollPane(productTable);

        // 加载商品数据
        loadProducts();

        // 创建输入面板
        JPanel inputPanel = new JPanel();
        inputPanel.setLayout(new BorderLayout());
        inputPanel.setBorder(BorderFactory.createTitledBorder("商品信息"));

        // 创建输入表单面板
        JPanel formPanel = new JPanel();
        formPanel.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 10, 5, 10);
        gbc.anchor = GridBagConstraints.WEST;

        // 商品名称
        JLabel productNameLabel = new JLabel("商品名称:");
        productNameField = new JTextField(15);
        gbc.gridx = 0;
        gbc.gridy = 0;
        formPanel.add(productNameLabel, gbc);
        gbc.gridx = 1;
        formPanel.add(productNameField, gbc);

        // 价格
        JLabel priceLabel = new JLabel("价格:");
        priceField = new JTextField(15);
        gbc.gridx = 2;
        gbc.gridy = 0;
        formPanel.add(priceLabel, gbc);
        gbc.gridx = 3;
        formPanel.add(priceField, gbc);

        // 类别
        JLabel categoryLabel = new JLabel("类别:");
        categoryField = new JTextField(15);
        gbc.gridx = 0;
        gbc.gridy = 1;
        formPanel.add(categoryLabel, gbc);
        gbc.gridx = 1;
        formPanel.add(categoryField, gbc);

        // 库存数量
        JLabel quantityLabel = new JLabel("库存数量:");
        quantityField = new JTextField(15);
        gbc.gridx = 2;
        gbc.gridy = 1;
        formPanel.add(quantityLabel, gbc);
        gbc.gridx = 3;
        formPanel.add(quantityField, gbc);

        // 添加到输入面板
        inputPanel.add(formPanel, BorderLayout.CENTER);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 15, 10));

        // 添加按钮
        addButton = new JButton("添加商品");
        deleteButton = new JButton("删除商品");
        updateButton = new JButton("修改商品");
        backButton = new JButton("返回");

        // 设置按钮样式
        Dimension buttonSize = new Dimension(120, 30);
        addButton.setPreferredSize(buttonSize);
        deleteButton.setPreferredSize(buttonSize);
        updateButton.setPreferredSize(buttonSize);
        backButton.setPreferredSize(buttonSize);

        // 添加按钮到面板
        buttonPanel.add(addButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(updateButton);
        buttonPanel.add(backButton);

        // 添加到输入面板
        inputPanel.add(buttonPanel, BorderLayout.SOUTH);

        // 添加事件监听器
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                addProduct();
            }
        });

        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                deleteProduct();
            }
        });

        updateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateProduct();
            }
        });

        backButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
                new AdminMainFrame(new Admin());
            }
        });

        // 添加到主面板
        mainPanel.add(scrollPane, BorderLayout.CENTER);
        mainPanel.add(inputPanel, BorderLayout.SOUTH);

        // 添加到窗口
        add(mainPanel);

        // 设置界面风格
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            SwingUtilities.updateComponentTreeUI(this);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 显示窗口
        setVisible(true);
    }

    private void addProduct() {
        String productName = productNameField.getText().trim();
        String priceText = priceField.getText().trim();
        String category = categoryField.getText().trim();
        String quantityText = quantityField.getText().trim();

        if (productName.isEmpty() || priceText.isEmpty() || category.isEmpty() || quantityText.isEmpty()) {
            JOptionPane.showMessageDialog(this, "所有字段不能为空！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        double price;
        int quantity;
        try {
            price = Double.parseDouble(priceText);
            quantity = Integer.parseInt(quantityText);
            if (quantity <= 0) {
                JOptionPane.showMessageDialog(this, "库存数量必须大于 0！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this, "价格和库存数量必须为数字！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        Product product = new Product();
        product.setProductName(productName);
        product.setPrice(price);
        product.setCategory(category);
        product.setQuantity(quantity);

        productDAO.addProduct(product);

        JOptionPane.showMessageDialog(this, "商品添加成功！", "成功", JOptionPane.INFORMATION_MESSAGE);

        productNameField.setText("");
        priceField.setText("");
        categoryField.setText("");
        quantityField.setText("");

        loadProducts();
    }

    private void deleteProduct() {
        int selectedRow = productTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择要删除的商品！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        int productId = (Integer) productTable.getValueAt(selectedRow, 0);

        productDAO.deleteProduct(productId);

        JOptionPane.showMessageDialog(this, "商品删除成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
        loadProducts();
    }

    private void updateProduct() {
        int selectedRow = productTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择要修改的商品！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        int productId = (Integer) productTable.getValueAt(selectedRow, 0);
        String productName = productNameField.getText().trim();
        String priceText = priceField.getText().trim();
        String category = categoryField.getText().trim();
        String quantityText = quantityField.getText().trim();

        if (productName.isEmpty() || priceText.isEmpty() || category.isEmpty() || quantityText.isEmpty()) {
            JOptionPane.showMessageDialog(this, "所有字段不能为空！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        double price;
        int quantity;
        try {
            price = Double.parseDouble(priceText);
            quantity = Integer.parseInt(quantityText);
            if (quantity <= 0) {
                JOptionPane.showMessageDialog(this, "库存数量必须大于 0！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this, "价格和库存数量必须为数字！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        Product product = new Product();
        product.setProductId(productId);
        product.setProductName(productName);
        product.setPrice(price);
        product.setCategory(category);
        product.setQuantity(quantity);

        productDAO.updateProduct(product);

        JOptionPane.showMessageDialog(this, "商品更新成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
        loadProducts();
    }

    private void loadProducts() {
        tableModel.setRowCount(0);
        List<Product> products = productDAO.getAllProducts();

        for (Product product : products) {
            Object[] row = {
                    product.getProductId(),
                    product.getProductName(),
                    product.getPrice(),
                    product.getCategory(),
                    product.getQuantity()
            };
            tableModel.addRow(row);
        }
    }

    public static void main(String[] args) {
        new ProductManageFrame();
    }
}